import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import { getToken, removeToken, isTokenExpired, getUserFromToken } from '../utils/auth';
import { apiRequest } from '../utils/api';

interface User {
  id: string;
  username: string;
  role: 'admin' | 'user';
}

interface AuthContextType {
  user: User | null;
  isAuthenticated: boolean;
  login: (token: string, userData: User) => void;
  logout: () => void;
  loading: boolean;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

interface AuthProviderProps {
  children: ReactNode;
}

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  const isAuthenticated = !!user;

  const login = (token: string, userData: User) => {
    localStorage.setItem('token', token);
    setUser(userData);
  };

  const logout = () => {
    removeToken();
    setUser(null);
  };

  // 初始化时检查token并获取用户信息
  useEffect(() => {
    const initAuth = async () => {
      const token = getToken();
      if (token) {
        // 首先检查token是否过期
        if (isTokenExpired(token)) {
          console.log('Token已过期，需要重新登录');
          removeToken();
          setLoading(false);
          return;
        }

        // 尝试从token中直接获取用户信息
        const userFromToken = getUserFromToken(token);
        if (userFromToken) {
          setUser({
            id: userFromToken.userId,
            username: userFromToken.username,
            role: userFromToken.role
          });
          setLoading(false);
          return;
        }

        // 如果无法从token获取用户信息，则向服务器验证
        try {
          const response = await apiRequest('/users/profile');
          if (response.success) {
            setUser(response.data);
          } else {
            console.log('服务器验证失败，清除token');
            removeToken();
          }
        } catch (error) {
          console.error('获取用户信息失败:', error);
          removeToken();
        }
      }
      setLoading(false);
    };

    initAuth();
  }, []);

  // 监听localStorage变化，当token被清除时自动登出
  useEffect(() => {
    const handleStorageChange = () => {
      const token = getToken();
      if (!token && user) {
        console.log('检测到token被清除，自动登出');
        setUser(null);
      }
    };

    // 监听localStorage变化
    window.addEventListener('storage', handleStorageChange);
    
    // 定期检查token是否还存在（用于同标签页内的变化）
    const intervalId = setInterval(() => {
      const token = getToken();
      if (!token && user) {
        console.log('检测到token被清除，自动登出');
        setUser(null);
      }
    }, 1000);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
      clearInterval(intervalId);
    };
  }, [user]);

  const value: AuthContextType = {
    user,
    isAuthenticated,
    login,
    logout,
    loading
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};
